<template>
	<BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="500px" @ok="handleSubmit">
		<BasicForm @register="registerForm">
			<template #menu="{ model, field }">
				<BasicTree v-model:value="model[field]" :treeData="treeData" :fieldNames="{ title: 'name', key: 'id' }" checkable toolbar title="菜单分配" />
			</template>
		</BasicForm>
	</BasicDrawer>
</template>
<script lang="ts">
	import { defineComponent, ref, computed, unref } from 'vue';
	import { BasicForm, useForm } from '/@/components/Form/index';
	import { formSchema } from './role.data';
	import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
	import { BasicTree, TreeItem } from '/@/components/Tree';
	import { menuList } from '/@/api/system/menu';
	import { roleSave } from '/@/api/system/role';

	export default defineComponent({
		name: 'RoleDrawer',
		components: { BasicDrawer, BasicForm, BasicTree },
		emits: ['success', 'register'],
		setup(_, { emit }) {
			const isUpdate = ref(true);
			const treeData = ref<TreeItem[]>([]);
			let noTreeData = [];

			const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
				labelWidth: 90,
				baseColProps: { span: 24 },
				schemas: formSchema,
				showActionButtonGroup: false,
			});

			const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
				resetFields();
				noTreeData = [];
				setDrawerProps({ confirmLoading: false });
				// 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
				if (unref(treeData).length === 0) {
					treeData.value = (await menuList({ queryParams: { "F_enabled_eq": 0 } })) as any as TreeItem[];
					//打平数据
					getNoTreeData(unref(treeData.value));
				}
				isUpdate.value = !!data?.isUpdate;

				if (unref(isUpdate)) {
					setFieldsValue({
						...data.record,
					});
				}
			});

			const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

			function getNoTreeData(treeData) {
				treeData.forEach(menu => {
					noTreeData.push(menu);
					if (menu.children && menu.children.length > 0) {
						getNoTreeData(menu.children);
					}
				});
			}


			async function handleSubmit() {
				try {
					const values = await validate();
					setDrawerProps({ confirmLoading: true });
					//这个地方 需要找到数据的所有上级 然后赋权所有上级数据信息
					let { menu } = values;
					const allMenu = [];

					menu.forEach(item => {
						let node = noTreeData.find(treeData => treeData.id == item);
						if (node && node.type != 0) {
							allMenu.push(item);
						}
					});
					await roleSave({
						...values,
						menu: allMenu
					});
					closeDrawer();
					emit('success');
				} finally {
					setDrawerProps({ confirmLoading: false });
				}
			}

			return {
				registerDrawer,
				registerForm,
				getTitle,
				handleSubmit,
				treeData,
			};
		},
	});
</script>